package com.qf.compusdemo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.compusdemo.dao.UserDao;
import com.qf.compusdemo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("UserDetail")
public class UserDetail implements UserDetailsService {
    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("username",username);
        System.out.println(username);
        User user=userDao.selectOne(wrapper);
        System.out.println(user);

        String name=user.getUsername();
        String password=user.getPassword();
        String auth=user.getAuth();
        System.out.println(name);


        //设置角色，角色的概念在之后章节介绍
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList(auth);
        //可以从数据库获取用户名和密码
        return new org.springframework.security.core.userdetails.User(name,new BCryptPasswordEncoder().encode(password),auths);
    }
}
